package com.tbit.uqbike.client.controller;

import cn.hutool.core.date.DateUtil;
import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.AdAccountFee;
import com.tbit.uqbike.client.pojo.RideLog;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.pojo.newEntity.BikePos;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.DateTimeUtil;
import com.tbit.uqbike.client.util.MoneyUtil;
import com.tbit.uqbike.client.util.OutputUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 骑行记录
 *
 * @author Leon
 * 2017年2月24日 下午5:51:05
 */
@RestController
@RequestMapping("/rideLog")
public class RideLogController {
    @Autowired
    private RideLogService rideLogService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private BikePosService bikePosService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private CacheService cacheService;

    /**
     * 查询用户骑行记录
     *
     * @param token    令牌
     * @param session  会话
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/getByUserId")
    public void getByUserId(String token, HttpSession session, HttpServletRequest request,
                            HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            User user = tokenService.getUser(token);

            List<RideLog> rideLogs = rideLogService.getByUserId(user.getUserId());

            if (rideLogs.size() > 0) {
                for (RideLog rideLog : rideLogs) {
                    rideLog.setExpired(1);
                    if (DateUtil.lastWeek().getTime() > DateUtil.parse(rideLog.getEndTime()).getTime()) {
                        rideLog.setExpired(0);
                    }
                }
            }
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, rideLogs);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }


    /**
     * 分页查询用户骑行记录
     *
     * @param token    令牌
     * @param rowCount 每页大小
     * @param pageNO   页码数
     * @param session  会话
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/queryPage")
    public void queryPage(String token, Integer rowCount, Integer pageNO, HttpSession session,
                          HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            User user = tokenService.getUser(token);

            /*默认值*/
            if (rowCount == null || rowCount < 1) {
                rowCount = 10;
            }
            if (pageNO == null || pageNO < 1) {
                pageNO = 1;
            }

            List<RideLog> rideLogs = rideLogService.queryPage(user.getUserId(), rowCount, pageNO);

            /*获取总数*/
            Integer count = rideLogService.queryCount(user.getUserId());
            map.put("total", count);

            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, rideLogs);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }


    /**
     * 通过订单编号获取借还车位置
     *
     * @param orderNO  订单编号
     * @param session
     * @param request
     * @param response
     */
    @RequestMapping("/getPos")
    public void getPos(String orderNO, HttpSession session, HttpServletRequest request,
                       HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            List<BikePos> list = bikePosService.getByOrderNO(orderNO);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, list);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    /**
     * 通过订单编号判断是否是短时骑行(免费骑行=短时骑行)
     *
     * @param orderNO  订单编号
     */
    @GetMapping("/isShortTimeRide")
    public void isShortTimeRide(String orderNO, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            RideLog rideLog = rideLogService.getByOrderNO(orderNO);
            int rideTime = (int) DateTimeUtil.getMinDiffer(rideLog.getStartTime(), rideLog.getEndTime());
            Integer distance = Optional.ofNullable(historyService.getMileageByMachineNOAndTime(rideLog.getMachineNO(),
                    rideLog.getStartTime(), rideLog.getEndTime())).orElse(0);
            AdAccountFee adAccountFee = cacheService.getAdAccountFee(rideLog.getAccountId(), rideLog.getMachineId());
            Integer freeTime = Optional.ofNullable(adAccountFee).map(o -> o.getFreeTime()).orElse(0);
            Integer freeDistance = Optional.ofNullable(adAccountFee).map(o -> o.getFreeDistance()).orElse(0);
            Integer freeConditionType = Optional.ofNullable(adAccountFee).map(o -> o.getFreeConditionType()).orElse(0);
            int freeType = MoneyUtil.countFreeType(rideTime, distance, freeTime, freeDistance, freeConditionType);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            if (freeType > 0){
                map.put(ResponseCode.DATA, true);
            }else {
                map.put(ResponseCode.DATA, false);
            }
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);

    }
}